package com.launcher.wkang.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.provider.Contacts;
import android.provider.ContactsContract;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;


import com.android.internal.telephony.ITelephony;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.launcher.wkang.activity.StudentSettingActivity;
import com.launcher.wkang.receive.PushReceive;

import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Hashtable;

import static android.graphics.Color.BLACK;
import static android.graphics.Color.WHITE;
import static android.provider.ContactsContract.SyncState.CONTENT_URI;

public class PhoneUtil {

    private static final int shutDownrequest=1001;
    private static final int caccelshutDownrequest=1002;
    private static final int startuprequest=1003;
    private static final int caccelstartuprequest=1004;

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static String getDeviceId(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }else {
            String imei = telephonyManager.getImei(1);
            return imei;
        }

    }

    // 一个添加联系人信息的例子
    public static void addContact(Context context,String name, String phoneNumber,long id) {
        // 创建一个空的ContentValues
        ContentValues values = new ContentValues();
        // 向RawContacts.CONTENT_URI空值插入，
        // 先获取Android系统返回的rawContactId
        // 后面要基于此id插入值
        Uri rawContactUri = context.getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);
        long rawContactId = ContentUris.parseId(rawContactUri);

        SharedPreferences sharedPreferences = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putLong(id+"", rawContactId);
        editor.commit();
        values.clear();
//        id=1234567892;

        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        // 内容类型
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        // 联系人名字
        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, name);
        // 向联系人URI添加联系人名字
        context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
        values.clear();

        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        // 联系人的电话号码
        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber);
        // 电话类型
        values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
        // 向联系人电话号码URI添加电话号码
        context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

        values.clear();

//        values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
//        values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
//        // 联系人的Email地址
//        values.put(ContactsContract.CommonDataKinds.Email.DATA, "zhangphil@xxx.com");
//        // 电子邮件的类型
//        values.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK);
//        // 向联系人Email URI添加Email数据
//        context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

        Toast.makeText(context, "联系人数据添加成功", Toast.LENGTH_SHORT).show();


//        ContentValues values1 = new ContentValues();
//        values.put(Contacts.People.NAME, name);
//        Uri uri = context.getContentResolver().insert(Contacts.People.CONTENT_URI,values1);
//        Uri numberUri = Uri.withAppendedPath(uri, Contacts.People.Phones.CONTENT_DIRECTORY);
//        values.clear(); values.put(Contacts.Phones.TYPE, Contacts.People.Phones.TYPE_MOBILE);
//        values.put(Contacts.People.NUMBER, phoneNumber);
//        context.getContentResolver().insert(numberUri, values);

    }
    // 一个添加联系人信息的例子
    public static void updateContact(Context context,String name, String phoneNumber,int id) {
        // 创建一个空的ContentValues
        ContentValues values = new ContentValues();
        ContentResolver cResolver = context.getContentResolver();
        SharedPreferences sharedPreferences = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);

        long rawContactId = sharedPreferences.getLong(id+"", 0);

        // 更新电话号码
        if (!TextUtils.isEmpty(phoneNumber)) {
            values.clear();
            // 更新电话号码
            values.put(ContactsContract.Data.DATA1, phoneNumber);
            int result = cResolver.update(ContactsContract.Data.CONTENT_URI, values, ContactsContract.Data.MIMETYPE + "=? and " + ContactsContract.PhoneLookup.NAME_RAW_CONTACT_ID + "=?",
                    new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, rawContactId+""});


        }

        // 更新联系人姓名
        values.clear();
        if (!TextUtils.isEmpty(name)){
            values.put(ContactsContract.Data.DATA2, name);
            int result = cResolver.update(ContactsContract.Data.CONTENT_URI, values, ContactsContract.Data.MIMETYPE + "=? and " + ContactsContract.PhoneLookup.NAME_RAW_CONTACT_ID + "=?",
                    new String[]{ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, rawContactId+""});

        }
        Toast.makeText(context, "联系人数据修改成功", Toast.LENGTH_SHORT).show();
    }
    // 删除联系人
    public static void deleteContact(Context context, long id) {


        // 创建一个空的ContentValues
        ContentValues values = new ContentValues();
        ContentResolver cResolver = context.getContentResolver();
        SharedPreferences sharedPreferences = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
        long rawContactId = sharedPreferences.getLong(id+"", 0);


        String where = ContactsContract.Data.RAW_CONTACT_ID;
        int deleteResult= cResolver.delete( ContactsContract.Data.CONTENT_URI, where + "=?", new String[]{rawContactId+""});
//        uri = ContactsContract.Data.CONTENT_URI;
//        cResolver.delete(uri, ContactsContract.Data.RAW_CONTACT_ID + "=?", new String[]{rawContactId + ""});
        Toast.makeText(context, "联系人数据删除成功", Toast.LENGTH_SHORT).show();

    }


    public static int getWindowWidth(Context context){
// 获取屏幕分辨率
        WindowManager wm = (WindowManager) (context.getSystemService(Context.WINDOW_SERVICE));
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int mScreenWidth = dm.widthPixels;
        return mScreenWidth;
    }


    public static void shutDown(int hour,int minutes,Context context ){
//        Calendar calendar = Calendar.getInstance();
//        long     nowTime  = calendar.getTimeInMillis();//这是当前的时间
//        Calendar myCal = Calendar.getInstance();
//        myCal.set(Calendar.HOUR_OF_DAY,hour);
//        myCal.set(Calendar.MINUTE,minutes);
//        long    shutDownTime = myCal.getTimeInMillis();
//        Intent intent = new Intent("com.android.settings.action.REQUEST_POWER_OFF");
//        Intent intent=new Intent(context,PushReceive.class);
//        intent.putExtra("getBroadcast","getBroadcast shutDown");
//        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, shutDownrequest,
//                intent, PendingIntent.FLAG_CANCEL_CURRENT);
//        PendingIntent pendingIntent = PendingIntent.getService(context,shutDownrequest,intent,0);
//        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
//            pendingIntent = PendingIntent.getForegroundService(context, shutDownrequest,
//                    intent, PendingIntent.FLAG_UPDATE_CURRENT);
//        }else{
//            pendingIntent = PendingIntent.getService(context, shutDownrequest,
//                    intent, PendingIntent.FLAG_UPDATE_CURRENT);
//        }
//        AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//        alarm.set(7,shutDownTime -nowTime, pendingIntent);
//        alarm.setExact(7,shutDownTime -nowTime, pendingIntent);
//        alarm.set(7,System.currentTimeMillis(),pendingIntent);
//        alarm.setRepeating(AlarmManager.RTC_WAKEUP ,
//                shutDownTime -nowTime, 1000*60*60*24, pendingIntent);//
//        if(Build.VERSION.SDK_INT < 19){
//            alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+1000 , pendingIntent);
//        }else{
//            alarm.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+1000 , pendingIntent);
//        }


        AlarmManager am = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);

//        Intent intent = new Intent("com.android.settings.action.REQUEST_POWER_OFF");

        Intent intent = new Intent(" android.intent.action.ACTION_SHUTDOWN");

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, shutDownrequest,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        am = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        am.set(7, System.currentTimeMillis()+500, pendingIntent);

    }

    public static void startUp(int hour,int minutes,Context context){

        Calendar calendar = Calendar.getInstance();
        long     nowTime  = calendar.getTimeInMillis();//这是当前的时间
        Calendar myCal = Calendar.getInstance();
        myCal.set(Calendar.HOUR_OF_DAY,hour);
        myCal.set(Calendar.MINUTE,minutes);
        long    shutDownTime = myCal.getTimeInMillis();
        Intent intent=new Intent("com.android.settings.action.ACTION_REQUEST_POWER_ON");
//        Intent intent=new Intent(context,PushReceive.class);
//        intent.putExtra("getBroadcast","getBroadcast");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, startuprequest,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

//        alarm.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), pendingIntent);
        if(Build.VERSION.SDK_INT < 19){
            alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+7*1000 , pendingIntent);
        }else{
            alarm.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+7*1000 , pendingIntent);
        }

//        alarm.setRepeating(7 ,
//                System.currentTimeMillis(), 1000*60*60*24, pendingIntent);
    }
    public static void cacellShutDown(Context context ){

        Intent intent= new Intent();
        intent.setAction("Intent.ACTION_REQUEST_SHUTDOWN");
        PendingIntent pendingIntent = PendingIntent.getService(context,caccelshutDownrequest,intent,0);
        AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(pendingIntent);

    }

    public static void cacellStartUp(Context context){
        Intent intent=new Intent("com.android.settings.action.ACTION_REQUEST_POWER_ON");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, caccelstartuprequest,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

        alarm.cancel(pendingIntent);

    }


    /**
     * 创建二维码位图
     *
     * @param content 字符串内容(支持中文)
     * @param width 位图宽度(单位:px)
     * @param height 位图高度(单位:px)
     * @return
     */

    public static Bitmap createQRCodeBitmap(String content, int width, int height){
        return createQRCodeBitmap(content, width, height, "UTF-8", "H", "2", Color.BLACK, Color.WHITE);
    }

    /**
     * 创建二维码位图 (支持自定义配置和自定义样式)
     *
     * @param content 字符串内容
     * @param width 位图宽度,要求>=0(单位:px)
     * @param height 位图高度,要求>=0(单位:px)
     * @param character_set 字符集/字符转码格式 (支持格式:{@link })。传null时,zxing源码默认使用 "ISO-8859-1"
     * @param error_correction 容错级别 (支持级别:{@link  })。传null时,zxing源码默认使用 "L"
     * @param margin 空白边距 (可修改,要求:整型且>=0), 传null时,zxing源码默认使用"4"。
     * @param color_black 黑色色块的自定义颜色值
     * @param color_white 白色色块的自定义颜色值
     * @return
     */

    public static Bitmap createQRCodeBitmap(String content, int width, int height,
                                            String character_set,  String error_correction,  String margin,
                                            int color_black,  int color_white){

        /** 1.参数合法性判断 */
        if(TextUtils.isEmpty(content)){ // 字符串内容判空
            return null;
        }

        if(width < 0 || height < 0){ // 宽和高都需要>=0
            return null;
        }

        try {
            /** 2.设置二维码相关配置,生成BitMatrix(位矩阵)对象 */
            Hashtable<EncodeHintType, String> hints = new Hashtable<>();

            if(!TextUtils.isEmpty(character_set)) {
                hints.put(EncodeHintType.CHARACTER_SET, character_set); // 字符转码格式设置
            }

            if(!TextUtils.isEmpty(error_correction)){
                hints.put(EncodeHintType.ERROR_CORRECTION, error_correction); // 容错级别设置
            }

            if(!TextUtils.isEmpty(margin)){
                hints.put(EncodeHintType.MARGIN, margin); // 空白边距设置
            }
            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

            /** 3.创建像素数组,并根据BitMatrix(位矩阵)对象为数组元素赋颜色值 */
            int[] pixels = new int[width * height];
            for(int y = 0; y < height; y++){
                for(int x = 0; x < width; x++){
                    if(bitMatrix.get(x, y)){
                        pixels[y * width + x] = color_black; // 黑色色块像素设置
                    } else {
                        pixels[y * width + x] = color_white; // 白色色块像素设置
                    }
                }
            }

            /** 4.创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,之后返回Bitmap对象 */
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
        }

        return null;
    }

    /** * 全透状态栏 */
    public static void setStatusBarFullTransparent(Activity activity) {
        if (Build.VERSION.SDK_INT >= 21) {
            //21表示5.0
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); }
        else if (Build.VERSION.SDK_INT >= 19) {
            //19表示4.4
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //虚拟键盘也透明 //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); }
        }
    }
    public static void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    public static  void setPowerSaveMode(boolean powerSave,Context context) {
        PowerManager mPowerManager  = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//        mPowerManager.setPowerSaveMode(powerSave);
        Class<PowerManager> c = PowerManager.class;
        try
        {
            Class[] cArg = new Class[1];
            cArg[0] = boolean.class;
            Method setPowerSaveModeMethod = c.getDeclaredMethod("setPowerSaveMode",  cArg);
            setPowerSaveModeMethod.setAccessible(true);
            setPowerSaveModeMethod.invoke(mPowerManager, powerSave);
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }

    }
    public static boolean getPowerSaveMode(Context context){
        PowerManager mPowerManager  = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        return mPowerManager.isPowerSaveMode();
    }

    }
